package com.xiaodong.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaodong.reggie.dto.SetmealDto;
import com.xiaodong.reggie.entity.DishFlavor;
import com.xiaodong.reggie.entity.Setmeal;
import com.xiaodong.reggie.entity.SetmealDish;
import com.xiaodong.reggie.mapper.SetmealMapper;
import com.xiaodong.reggie.service.SetmealDishService;
import com.xiaodong.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    //进行套餐和套餐中菜品的添加
    @Override
    @Transactional
    public void saveByDto(SetmealDto setmealDto) {

        //添加套餐
        this.save(setmealDto);

        //获取套餐id
        Long setmealId = setmealDto.getId();

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        //将套餐id添加到setmealDishes集合中
        setmealDishes = setmealDishes.stream().map((item) -> {

            item.setSetmealId(setmealId);

            return item;

        }).collect(Collectors.toList());

        //添加套餐id
        setmealDishService.saveBatch(setmealDishes);

    }

    //查询套餐和套餐中菜品的数据
    @Override
    public SetmealDto getDishAndFlavor(Long id) {

        //获取套餐数据
        Setmeal byId = this.getById(id);

        SetmealDto setmealDto = new SetmealDto();

        BeanUtils.copyProperties(byId, setmealDto);

        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SetmealDish::getSetmealId, byId.getId());

        List<SetmealDish> one = setmealDishService.list(queryWrapper);

        setmealDto.setSetmealDishes(one);

        return setmealDto;
    }

    //修改套餐和套餐中菜品的数据
    @Override
    @Transactional
    public void updateDishAndFlavor(SetmealDto setmealDto) {

        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto, setmeal, "setmealDishes,categoryName");

        this.updateById(setmeal);

        List<SetmealDish> flavors = setmealDto.getSetmealDishes();

        //删除套餐中菜品表里的记录

        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(queryWrapper);

        //将套餐id添加到flavors集合中
        flavors = flavors.stream().map((item) -> {

            item.setSetmealId(setmealDto.getId());

            return item;

        }).collect(Collectors.toList());

        //添加套餐菜品
        setmealDishService.saveBatch(flavors);

    }
}
